import { Button, Dialog, Form, Input, Radio, Select } from '@alicloudfe/components';
import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import styles from './index.module.less';
import { getModelList, saveConfiguredModelKey } from '@/AI/apis';
import { IModelInfo, IRequestSetModel, IUserConfiguredModelInfo } from '@/AI/ai';

const ModelConfigDialog = forwardRef((props: {
  onSave?: () => void;
}, ref) => {
  const {
    onSave = () => {},
  } = props;


  const [visible, setVisible] = useState(false);
  const closeDialog = () => {
    setVisible(false);
  };


  const [isEditing, setIsEditing] = useState(false);

  // 后端目前支持的模型列表
  const [supportedModelList, setSupportedModelList] = useState<IModelInfo[]>([]);
  useEffect(() => {
    getModelList().then((res) => {
      setSupportedModelList(res);
    });
  }, []);

  const [modelVersionList, setModelVersionList] = useState<IModelInfo['versionList']>([]);


  const [modelFormData, setModelFormData] = useState<IRequestSetModel>({} as any);

  const updateModelFormData = (value: Partial<IRequestSetModel>) => {
    setModelFormData({
      ...modelFormData,
      ...value,
    });
  };

  useEffect(() => {
    const targetModel = supportedModelList.find((i) => i.id === modelFormData.modelId) || { versionList: [] as string[] };
    const list = targetModel?.versionList || [];
    setModelVersionList(list as any);
  }, [modelFormData.modelId, supportedModelList]);

  const saveNewKey = () => {
    saveConfiguredModelKey({
      ...modelFormData,
      version: (modelFormData.version as string[]).join(','),
    }).then(() => {
      onSave();
      closeDialog();
    });
  };

  useImperativeHandle(ref, () => ({
    editModelKey,
  }));
  // 编辑模型
  const editModelKey = (data: IUserConfiguredModelInfo) => {
    const isEdit = data.id;

    if (isEdit) {
      setIsEditing(true);
    } else {
      setIsEditing(false);
    }
    const dataCopy: IUserConfiguredModelInfo = JSON.parse(JSON.stringify(data));
    const temp: IRequestSetModel = {
      ...dataCopy,
      version: dataCopy.version ? dataCopy.version.split(',') : null,
      customModelName: dataCopy.name,
    };
    setModelFormData(temp);
    setVisible(true);
  };

  return (
    <Dialog
      v2
      title={isEditing ? '编辑 AI' : '添加 AI'}
      visible={visible}
      footer={false}
      onClose={closeDialog}
      style={{
        width: '50%',
      }}
    >
      <Form
        fullWidth
        labelAlign="top"
        value={modelFormData}
        className={styles.addingKeyForm}
      >
        <Form.Item
          label="AI 名称"
          required
          name="modelId"
          requiredMessage="请选择 AI 模型"
          disabled={isEditing}
          autoValidate={false}
        >
          <Radio.Group
            value={modelFormData.modelId}
            onChange={(value) => {
              updateModelFormData({
                modelId: value as string,
                version: undefined,
              });
            }}
          >
            {
              supportedModelList.map((model) => (
                <Radio
                  key={model.id}
                  value={model.id}
                  id={model.id}
                >
                  <div className={styles.modelInfos}>
                    <img
                      className={styles.modelIcon}
                      src={model.icon}
                    />
                    <span>{model.name}</span>
                  </div>
                </Radio>
              ))
            }
          </Radio.Group>

        </Form.Item>
        {
          modelFormData.modelId && (
            <Form.Item
              label="AI 版本"
              required
              requiredMessage="请选择模型版本"
              name="version"
              disabled={isEditing}
            >
              <Select
                mode="multiple"
                onChange={(value = []) => {
                  updateModelFormData({
                    version: value,
                  });
                }}
                style={{ width: '100%' }}
              >
                {
                  modelVersionList.map((versionObj) => (
                    <Select.Option
                      key={versionObj.version}
                      value={versionObj.version}
                    >
                      {versionObj.version}
                    </Select.Option>
                  ))
                }
              </Select>
            </Form.Item>
          )
        }
        {
          modelFormData.modelId && (
            (supportedModelList.find((model) => model.id === modelFormData.modelId)?.authParams || ['apiKey']).map((item) => {
              return (
                <Form.Item
                  label={item}
                  key={item}
                  required
                  requiredMessage={`请填写${item}`}
                  name={item}
                  extra={
                    item === 'apiKey' ? (
                      <p style={{ marginTop: '4px' }}>
                        不知道怎么获取自己的 token/key？<a href="https://docs.atomgit.com/ai/ai/aiUse" target="_blank" rel="noreferrer">点击此处</a>查看教程。
                      </p>
                    ) : ''
                  }
                >
                  <Input
                    value={modelFormData[item as keyof IRequestSetModel] as string}
                    onChange={(value) => {
                      updateModelFormData({
                        [item]: value,
                      });
                    }}
                    placeholder={`请输入您的${item}`}
                  />
                </Form.Item>
              );
            })
          )
        }
        <Form.Item
          style={{
            display: 'flex',
            justifyContent: 'flex-end',
            marginBottom: 'unset',
          }}
        >
          <Button
            style={{
              marginRight: 8,
            }}
            onClick={() => {
              closeDialog();
            }}
          >
            取消
          </Button>
          <Form.Submit
            validate
            type="primary"
            onClick={(values, errors) => {
              if (!errors) {
                saveNewKey();
              }
            }}
          >
            保存
          </Form.Submit>
        </Form.Item>
      </Form>
    </Dialog>
  );
});

export default ModelConfigDialog;
